<template>
  <div class="app-container">
    <!-- 试卷基本信息 -->
    <el-card class="box-card" style="margin-bottom: 20px;">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; font-weight: bold;">试卷信息</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="$router.go(-1)">返回</el-button>
      </div>
      <el-row>
        <el-col :span="12">
          <div class="info-item">
            <label>试卷标题：</label>
            <span>{{ paperInfo.title }}</span>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="info-item">
            <label>考试时长：</label>
            <span>{{ paperInfo.duration }}分钟</span>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="info-item">
            <label>题目数量：</label>
            <span>{{ paperInfo.questionCount || 0 }}题</span>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="info-item">
            <label>总分：</label>
            <span>{{ paperInfo.totalScore || 0 }}分</span>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="info-item">
            <label>试卷描述：</label>
            <span>{{ paperInfo.description || '暂无描述' }}</span>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="info-item">
            <label>状态：</label>
            <el-tag :type="statusTagType(paperInfo.status)">
              {{ statusText(paperInfo.status) }}
            </el-tag>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="info-item">
            <label>创建时间：</label>
            <span>{{ paperInfo.createTime }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 题目管理 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 16px; font-weight: bold;">题目管理</span>
        <el-button-group style="float: right;">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="showAddQuestionDialog">
            添加题目
          </el-button>
          <el-button size="small" type="success" icon="el-icon-magic-stick" @click="showAutoComposeDialog">
            自动组卷
          </el-button>
        </el-button-group>
      </div>

      <!-- 题目列表 -->
      <el-table
        v-loading="questionLoading"
        :data="questionList"
        border
        style="width: 100%"
      >
        <el-table-column prop="questionOrder" label="序号" width="80" align="center" />
        <el-table-column prop="title" label="题目标题" min-width="200" />
        <el-table-column prop="questionType" label="题型" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="questionTypeTagType(scope.row.questionType)">
              {{ questionTypeText(scope.row.questionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="difficultyLevel" label="难度" width="80" align="center">
          <template slot-scope="scope">
            <el-tag :type="difficultyTagType(scope.row.difficultyLevel)">
              {{ scope.row.difficultyLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="questionScore" label="分值" width="80" align="center" />
        <el-table-column label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="removeQuestionFromPaper(scope.row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加题目对话框 -->
    <el-dialog title="添加题目" :visible.sync="addQuestionDialogVisible" width="80%">
      <div class="filter-container">
        <el-select v-model="questionQuery.categoryId" placeholder="选择分类" clearable style="width: 150px;" class="filter-item">
          <el-option v-for="category in categoryList" :key="category.categoryId" :label="category.name" :value="category.categoryId" />
        </el-select>
        <el-select v-model="questionQuery.questionType" placeholder="选择题型" clearable style="width: 120px;" class="filter-item">
          <el-option label="单选题" value="single_choice" />
          <el-option label="多选题" value="multiple_choice" />
          <el-option label="判断题" value="true_false" />
          <el-option label="简答题" value="essay" />
        </el-select>
        <el-select v-model="questionQuery.difficultyLevel" placeholder="选择难度" clearable style="width: 100px;" class="filter-item">
          <el-option label="简单" value="简单" />
          <el-option label="中等" value="中等" />
          <el-option label="困难" value="困难" />
        </el-select>
        <el-input v-model="questionQuery.title" placeholder="题目标题" style="width: 200px;" class="filter-item" />
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="searchQuestions">搜索</el-button>
      </div>

      <el-table
        ref="questionTable"
        v-loading="searchLoading"
        :data="availableQuestions"
        border
        style="width: 100%; margin-top: 20px;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="题目标题" min-width="200" />
        <el-table-column prop="questionType" label="题型" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="questionTypeTagType(scope.row.questionType)">
              {{ questionTypeText(scope.row.questionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="difficultyLevel" label="难度" width="80" align="center">
          <template slot-scope="scope">
            <el-tag :type="difficultyTagType(scope.row.difficultyLevel)">
              {{ scope.row.difficultyLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="默认分值" width="100" align="center" />
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addQuestionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addSelectedQuestions">添加选中题目</el-button>
      </div>
    </el-dialog>

    <!-- 自动组卷对话框 -->
    <el-dialog title="自动组卷" :visible.sync="autoComposeDialogVisible" width="500px">
      <el-form ref="autoComposeForm" :model="autoComposeForm" label-width="120px">
        <el-form-item label="选择分类">
          <el-select v-model="autoComposeForm.categoryId" placeholder="请选择分类" clearable>
            <el-option v-for="category in categoryList" :key="category.categoryId" :label="category.name" :value="category.categoryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度等级">
          <el-select v-model="autoComposeForm.difficultyLevel" placeholder="请选择难度" clearable>
            <el-option label="简单" value="简单" />
            <el-option label="中等" value="中等" />
            <el-option label="困难" value="困难" />
          </el-select>
        </el-form-item>
        <el-form-item label="题目数量">
          <el-input-number v-model="autoComposeForm.questionCount" :min="1" :max="100" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="autoComposeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="autoCompose">开始组卷</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDetail, addQuestions, removeQuestion, autoCompose } from '@/api/paperApi'
import questionManger from '@/api/questionManger'
import categoryManger from '@/api/categoryManger'

export default {
  name: 'PaperDetail',
  data() {
    return {
      paperId: null,
      paperInfo: {},
      questionList: [],
      questionLoading: false,

      // 添加题目相关
      addQuestionDialogVisible: false,
      availableQuestions: [],
      selectedQuestions: [],
      searchLoading: false,
      questionQuery: {
        categoryId: null,
        questionType: null,
        difficultyLevel: null,
        title: null
      },

      // 自动组卷相关
      autoComposeDialogVisible: false,
      autoComposeForm: {
        categoryId: null,
        difficultyLevel: null,
        questionCount: 10
      },

      // 基础数据
      categoryList: []
    }
  },
  created() {
    this.paperId = this.$route.params.id
    console.log('试卷ID:', this.paperId)
    console.log('路由参数:', this.$route.params)
    this.loadPaperDetail()
    this.loadCategories()
  },
  methods: {
    async loadPaperDetail() {
      try {
        this.questionLoading = true
        const response = await getDetail(this.paperId)
        this.paperInfo = response.data
        this.questionList = response.data.questions || []
      } catch (error) {
        this.$message.error('加载试卷详情失败')
        console.error('加载试卷详情失败:', error)
      } finally {
        this.questionLoading = false
      }
    },

    async loadCategories() {
      try {
        const response = await categoryManger.getAllCategoriesApi()
        this.categoryList = response.data
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    },

    showAddQuestionDialog() {
      this.addQuestionDialogVisible = true
      this.searchQuestions()
    },

    async searchQuestions() {
      try {
        this.searchLoading = true
        const params = {
          currentPage: 1,
          pageSize: 50,
          categoryId: this.questionQuery.categoryId,
          questionType: this.questionQuery.questionType,
          difficultyLevel: this.questionQuery.difficultyLevel,
          title: this.questionQuery.title
        }
        const response = await questionManger.getTableDataApi(params)
        this.availableQuestions = response.data.questions || []
      } catch (error) {
        this.$message.error('搜索题目失败')
        console.error('搜索题目失败:', error)
      } finally {
        this.searchLoading = false
      }
    },

    handleSelectionChange(selection) {
      this.selectedQuestions = selection
    },

    async addSelectedQuestions() {
      if (this.selectedQuestions.length === 0) {
        this.$message.warning('请选择要添加的题目')
        return
      }

      try {
        const questionIds = this.selectedQuestions.map(q => q.questionId)
        await addQuestions(this.paperId, questionIds)
        this.$message.success('题目添加成功')
        this.addQuestionDialogVisible = false
        this.loadPaperDetail()
      } catch (error) {
        this.$message.error('添加题目失败')
        console.error('添加题目失败:', error)
      }
    },

    async removeQuestionFromPaper(question) {
      try {
        await this.$confirm(`确定要移除题目"${question.title}"吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await removeQuestion(this.paperId, question.questionId)
        this.$message.success('题目移除成功')
        this.loadPaperDetail()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('移除题目失败')
          console.error('移除题目失败:', error)
        }
      }
    },

    showAutoComposeDialog() {
      this.autoComposeDialogVisible = true
    },

    async autoCompose() {
      try {
        await autoCompose(this.paperId, this.autoComposeForm.categoryId, this.autoComposeForm.difficultyLevel, this.autoComposeForm.questionCount)
        this.$message.success('自动组卷成功')
        this.autoComposeDialogVisible = false
        this.loadPaperDetail()
      } catch (error) {
        this.$message.error('自动组卷失败')
        console.error('自动组卷失败:', error)
      }
    },

    statusTagType(status) {
      const statusMap = {
        draft: '',
        published: 'success',
        archived: 'info'
      }
      return statusMap[status]
    },

    statusText(status) {
      const statusMap = {
        draft: '草稿',
        published: '已发布',
        archived: '已归档'
      }
      return statusMap[status] || status
    },

    questionTypeTagType(type) {
      const typeMap = {
        single_choice: 'primary',
        multiple_choice: 'success',
        true_false: 'warning',
        essay: 'info'
      }
      return typeMap[type]
    },

    questionTypeText(type) {
      const typeMap = {
        single_choice: '单选题',
        multiple_choice: '多选题',
        true_false: '判断题',
        essay: '简答题'
      }
      return typeMap[type] || type
    },

    difficultyTagType(difficulty) {
      const difficultyMap = {
        '简单': 'success',
        '中等': 'warning',
        '困难': 'danger'
      }
      return difficultyMap[difficulty]
    }
  }
}
</script>

<style scoped>
.info-item {
  margin-bottom: 15px;
}

.info-item label {
  font-weight: bold;
  margin-right: 10px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-item {
  margin-right: 10px;
}
</style>
